package com.cloudeasy.post.controller;

import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.core.bean.JwtParser;
import com.cloudeasy.post.po.Post;
import com.cloudeasy.post.service.PostLabelService;
import com.cloudeasy.post.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/label")
public class PostLabelController {
    private final PostService postService;

    private final PostLabelService postLabelService;

    private final JwtParser jwtParser;

    @Autowired
    public PostLabelController(PostService postService, PostLabelService postLabelService, JwtParser jwtParser) {
        this.postService = postService;
        this.postLabelService = postLabelService;
        this.jwtParser = jwtParser;
    }

    /**
     * 设置文章标签
     * @param authentication {@link Authentication}
     * @param postId         文章Id
     * @param labelIds       标签Id列表
     * @return {@link Result<Boolean>}
     */
    @PutMapping("/{postId}")
    public Result<Boolean> setLabel(Authentication authentication,
                                    @PathVariable("postId") String postId,
                                    @RequestParam("labelIds") List<String> labelIds) {
        String userId = (String) jwtParser.getOnBody(authentication, "userId");
        Post post = postService.getById(postId);
        if (post == null) {
            throw new CloudEasyException(ResultCodeEnum.ID_NOT_EXISTS);
        }
        if (!userId.equals(post.getAuthorId())){
            throw new CloudEasyException(ResultCodeEnum.NO_PERMISSION_OPERATE);
        }
        return ResultUtil.success(postLabelService.update(postId, labelIds));
    }
}
